//
// Created by lei chen on 2017/3/14.
//

#include <fstream>
#include "OtherAlgorithm.h"
#define RANDOM(x) (rand()%(x))

vector<int> OtherAlgorithm::getReservoirSample(int k, string filePath) {
    vector<int> ret ;
    string lineStr ;
    int lineNum = 0;
    fstream fin(filePath) ;
    srand((int)time(0));
    while(getline(fin,lineStr)){
        if(lineNum < k){
            ret.push_back(lineNum) ;
        }else{

            int r = RANDOM(lineNum+1) ;
            //  第i个 以  k / i 概率 被选中并随机替换蓄水池中元素
            if( r  < k){
                ret[r] = lineNum ;
           }
        }
        lineNum++ ;
    }
    return  ret ;
}

void OtherAlgorithm::testMain() {
    cout << "OtherAlgorithm::testMain" << endl ;
    vector<int> ret = getReservoirSample(5,"/Users/leichen/CLionProjects/MicrosoftCode/other/files/testReservoirFile") ;
    for (vector<int>::iterator iter = ret.begin(); iter < ret.end() ; iter ++) {
        cout << *iter << endl ;
    }
}

